#!/usr/bin/env python
# Location Changer
import os, syslog, time, sys

def parseTable(tablefile, transitionstable):
	if not os.path.isfile(tablefile):
		print 'Warning: ' + tablefile + ' is not a file'
		return -1
	try:
		fh = open(tablefile, 'r')
		for line in fh:
			line = line.strip()
			if line[0] != '#':
				# then its not a comment
				parts = line.split(' ',2)
				origin = parts.pop(0).strip()
				dest = parts.pop(0).strip()
				command = parts.pop(0).strip()
				# check things exist first
				if(transitionstable.get(origin,None)) == None: transitionstable[origin] = dict()
				if(transitionstable[origin].get(dest,None)) == None: transitionstable[origin][dest] = [];
				# then put it in
				transitionstable[origin][dest].append(command)
	except Exception, e:
		print('Failed to parse file: ' + str(e))
		return -1
	
def main():
	# Get the current location 
	currentlocation = os.popen('scselect 2>&1|awk \'$1 ~ /\*/ {gsub("[()]","",$3);print $3}\'').read().strip()
	# Try to get the old location
	try:
		oldlocation = open('/var/log/lastlocation','r').read().strip()
	except:
		oldlocation = ''
			
	if currentlocation == oldlocation:
		print 'Warning: Transitioned to the same location'
		#sys.exit(0)
		
	# Try to get the new location
	try:
		lastlocfile = open('/var/log/lastlocation','w')
		lastlocfile.write(currentlocation)
		lastlocfile.close()
	except Exception, e:
		# This isn't critical, it might be debugging
		print 'Error updating last location: ' + str(e)
	
	print 'Current Location: %s' % currentlocation
	print 'Previous Location: %s' % oldlocation
	
	transitions = dict()	
	parseTable('/etc/locationtab', transitions)
	# note: update this to include every user
	# print transitions
	try:
		for command in transitions.get('*').get('*'):
		#	print 'Wildcard command: ' + command
			print os.popen(command).read()
	except Exception, e:
		#print str(e)
		None
		
	try:
		for command in transitions.get(oldlocation).get('*'):
		#	print 'Wildcard destination: ' + command
			print os.popen(command).read()
	except Exception, e:
		#print str(e)
		None
		
	try:
		for command in transitions.get('*').get(currentlocation):
		#	print 'Wildcard origin: ' + command
			print os.popen(command).read()
	except Exception, e:
		#print str(e)
		None
		
	try:
		for command in transitions.get(oldlocation).get(currentlocation):
		#	print 'Full origin destination match: ' + command
			print os.popen(command).read()
	except Exception, e:
		#print str(e)
		None
	
	# Boo
	
	sys.exit(0)

if __name__ == '__main__':
	main()
